package com.enjoy.xbase.xui.views;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;

import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.enjoy.xbase.R;
import com.enjoy.xbase.xui.adapter.BaseRvAdapter;
import com.enjoy.xbase.xui.adapter.BaseRvViewHolder;
import com.enjoy.xbase.xui.listener.ILoadRefresh;
import com.enjoy.xbase.xui.load.BaseLoad;
import com.enjoy.xbase.xui.load.LoadView;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

public class RefreshListView extends RelativeLayout {
    private Context mContext;

    protected View rootView;
    protected LoadView loadView;
    protected SmartRefreshLayout smartRefreshLayout;
    protected RecyclerView recyclerView;
    protected BaseRvAdapter adapter;

    //管理
    protected List data = new ArrayList();
    protected int page = 0;//从第一页开始
    private boolean mNoMoreData;//无更多数据

    //设置值
    private int column=1;
    private boolean hasFooter;//是否有底部
    private int footerLayoutId;//底部视图
    private boolean flowModel;//是否流式布局
    private boolean canLoadMore;

    private DataHelper dataHelper;

    public RefreshListView(Context context) {
        super(context);
        initView(context);
    }

    public RefreshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public RefreshListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    protected final void initView(Context context) {
        this.mContext=context;
        rootView= inflate(getContext(), R.layout.xbase_base_list_v3, this);
        loadView = rootView.findViewById(R.id.x_load);
        recyclerView = rootView.findViewById(R.id.x_rv);
        smartRefreshLayout = rootView.findViewById(R.id.x_smart_refresh);
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                dataHelper.requestData(page = 0);
            }
        });
        smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                dataHelper.requestData(++page);
            }
        });
        //设置刷新事件
        loadView.setLoadRefresh(new ILoadRefresh() {
            @Override
            public void onRefresh() {
                dataHelper.requestData(page = 0);
            }
        });
        onInitBaseComplete();
    }
    private void initListView(){
        if (column==1||column==-1) {
            //创建LinearLayoutManager 对象 这里使用 LinearLayoutManager 是线性布局的意思
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
            linearLayoutManager.setOrientation(column>0?RecyclerView.VERTICAL:RecyclerView.HORIZONTAL);
            //设置RecyclerView 布局
            recyclerView.setLayoutManager(linearLayoutManager);
        } else {
            if (flowModel){
                StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(Math.abs(column), column>0?StaggeredGridLayoutManager.VERTICAL:StaggeredGridLayoutManager.HORIZONTAL);
                //防止item交换位置
                staggeredGridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);

                recyclerView.setLayoutManager(staggeredGridLayoutManager);
            }else{
                //布局管理器所需参数，上下文
                GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, Math.abs(column));
                //B 通过布局管理器，可以控制条目排列顺序  true：反向显示  false：正常显示(默认)
                gridLayoutManager.setReverseLayout(false);
                //C 设置RecyclerView显示的方向，是水平还是垂直！！ GridLayoutManager.VERTICAL(默认) false
                gridLayoutManager.setOrientation(column>0?RecyclerView.VERTICAL:RecyclerView.HORIZONTAL);
                gridLayoutManager.setAutoMeasureEnabled(true);
                recyclerView.setLayoutManager(gridLayoutManager);
            }
        }
        if (adapter==null) {
            //设置Adapter
            adapter = new BaseRvAdapter(mContext, new BaseRvAdapter.IDataView() {
                @Override
                public int getItemCount() {
                    if (data.size() > 0) {
                        return (mNoMoreData && hasFooter) ? data.size() + 1 : data.size();
                    } else {
                        return 0;
                    }
                }

                @Override
                public int getItemViewType(int position) {
                    if (position < data.size()) {
                        return dataHelper.getItemViewType(position);
                    } else {
                        return -1;
                    }
                }

                @Override
                public int getItemLayoutId(int viewType) {
                    if (mNoMoreData && hasFooter && viewType == -1) {
                        return footerLayoutId;
                    } else {
                        return dataHelper.getItemLayoutId(viewType);
                    }
                }

                @Override
                public void onBindViewHolder(BaseRvViewHolder holder, int position) {
                    if (mNoMoreData && hasFooter && data.size()  == position) {
                        dataHelper.onBindViewHolder(holder,2, position);
                    } else {
                        dataHelper.onBindViewHolder(holder,1, position);
                    }
                }
            });
            recyclerView.setAdapter(adapter);
        }
    }

    /**
     * 基类初始化完成
     */
    protected void onInitBaseComplete(){

    }





    public View getXRootView() {
        return rootView;
    }

    public void xInit(){
        if (adapter==null){
            initListView();
        }
    }
    public void xInitAndData(){
        if (adapter==null){
            initListView();
        }
        loadView.showLoad();
        dataHelper.requestData(page = 0);
    }

    public void setEnableRefresh(boolean enabled){
        smartRefreshLayout.setEnableRefresh(enabled);
    }
    public void setEnableLoadMore(boolean enabled){
        this.canLoadMore=enabled;
        smartRefreshLayout.setEnableLoadMore(enabled);
    }
    public void setListColumn(int column) {
        this.column = column;
    }

    public void setFlowModel(boolean flowModel) {
        this.flowModel = flowModel;
    }

    public void setHasFooter(boolean hasFooter, int footerLayoutId) {
        this.hasFooter = hasFooter;
        this.footerLayoutId=footerLayoutId;
        if (adapter!=null){
            adapter.notifyDataSetChanged();
        }
    }
    /**
     * 描述：设置数据层颜色
     */
    public void setDataBgColor(@ColorInt int color) {
        if (recyclerView != null) recyclerView.setBackgroundColor(color);
    }
    public void setLoad(BaseLoad load){
        loadView.setLoad(load);
    }
    /**
     * 描述：设置数据层颜色
     */
    public void setLoadBgColor(@ColorInt int color) {
        loadView.setBackgroundColor(color);
    }

    public void setDataHelper(DataHelper dataHelper) {
        this.dataHelper = dataHelper;
    }

    public void refreshData() {
        dataHelper.requestData(page = 0);
    }

    public void refreshAndLoad() {
        if (loadView == null) {
            throw new RuntimeException("loadView未初始化");
        }
        loadView.showLoad();
        dataHelper.requestData(page = 0);
    }

    public void refreshAndLoading() {
        if (loadView == null) {
            throw new RuntimeException("loadView未初始化");
        }
        loadView.showLoading();
        dataHelper.requestData(page = 0);
    }


    /**
     * 描述：设置请求后的数据
     *
     * @param page
     * @param data null-失败
     */
    public void setRequestData(int page, List data){
        setRequestData(page,data,false,null);
    }
    public void setRequestData(int page, List data,boolean isEnd,Object param) {
        if (page == 0) {
            if (data == null) {
                this.data.clear();
                this.notifyDataSetChanged();
                loadView.showFail(param);
            } else {
                if (data.size() == 0) {
                    loadView.showEmpty(param);
                    setNoMoreData(true);
                } else {
                    if (isEnd){
                        setNoMoreData(true);
                    }else{
                        setNoMoreData(false);
                    }
                    loadView.showData();
                }
                this.data.clear();
                this.data.addAll(data);
                this.notifyDataSetChanged();
            }
            smartRefreshLayout.finishRefresh();
        } else {
            if (data == null) {
                --this.page;
                loadView.showData();
            } else if (data.size() == 0) {
                setNoMoreData(true);
                loadView.showData();
            } else {
                if (isEnd){
                    setNoMoreData(true);
                }else{
                    setNoMoreData(false);
                }
                if (flowModel){
                    int start=this.data.size();
                    this.data.addAll(data);
                    this.adapter.notifyItemRangeInserted(start,data.size());
                    loadView.showData();
                }else{
                    this.data.addAll(data);
                    this.notifyDataSetChanged();
                    loadView.showData();
                }
            }
            smartRefreshLayout.finishLoadMore();
        }
    }

    public <T> T getData(int position) {
        return (T) data.get(position);
    }

    public <T> List<T> getAllData() {
        return data;
    }
    public void removeData(Object object) {
        data.remove(object);
        if (data.size() == 0) {
            loadView.showEmpty();
        }
        notifyDataSetChanged();
    }

    public void notifyDataSetChanged() {
        adapter.notifyDataSetChanged();
    }

    public SmartRefreshLayout getSmartRefreshLayout() {
        return smartRefreshLayout;
    }

    public RecyclerView getRecyclerView() {
        return recyclerView;
    }
    /**
     * 描述：获取适配器
     * @return
     */
    public BaseRvAdapter getAdapter() {
        return adapter;
    }

    /**
     * 描述： 返回是否滑动到顶部
     */
    public boolean isToTop() {
        if (recyclerView != null) {
            return !recyclerView.canScrollVertically(-1);
        }
        return true;
    }

    /**
     * 描述：返回是否滑动到底部
     *
     * @return
     */
    public boolean isToBottom() {
        if (recyclerView != null) {
            return !recyclerView.canScrollVertically(1);
        }
        return true;
    }

    private void setNoMoreData(boolean noMoreData) {
        this.mNoMoreData=noMoreData;
        if (noMoreData){
            smartRefreshLayout.setEnableLoadMore(false);
        }else{
            if (canLoadMore) {
                smartRefreshLayout.setEnableLoadMore(true);
            }else {
                smartRefreshLayout.setEnableLoadMore(false);
            }
        }
    }

    public interface DataHelper{
        /**
         * 描述 数据加载 通过 setRequestData
         * @param page
         */
        void requestData(int page);

        int getItemViewType(int position);

        int getItemLayoutId(int viewType);
        /**
         * @param type 1-数据结构类型 2-footer
         */
        void onBindViewHolder(BaseRvViewHolder holder, int type, int position);
    }
}
